<?php
/**
 * 分类模型管理
 * @author cjli
 *
 */
class CategoryModel extends Model
{
	const TYPE_CATEGORY = 1; //产品分类
	const TYPE_ARTICLE = 2; //文章分类
	const TYPE_BRAND = 3; //品牌分类
	const TYPE_ARTICLE_RECOMMEND = 4; //文章推荐分类
	const TYPE_RECOMMEND = 5; //产品推荐分类
	const TYPE_PROBLEM_TYPES = 6; //问题分类
	const TYPE_PRODUCTION = 7; //作品分类
	const TYPE_STYLE = 8; //类型属性管理
	const TYPE_colour = 9; //类型属性管理（颜色）

	public $vocabularyType = array(
    self::TYPE_CATEGORY => 'category',
    self::TYPE_ARTICLE => 'article',
    self::TYPE_BRAND => 'brand',
    self::TYPE_ARTICLE_RECOMMEND => 'article_recommend',
    self::TYPE_RECOMMEND => 'recommend',
	self::TYPE_PROBLEM_TYPES => 'problem_types',
	self::TYPE_PRODUCTION => 'production',
  );
	/**
   * 获取所有分类信息列表
   * @return object 分类列表信息
   */
  public static function get_vocabulary_list()
  {
  	$category = array();
		if(S('vocabulary_list')){
			$category = S('vocabulary_list');
		}else{
			$vocabularydb = D('vocabulary');
			$result = $vocabularydb->select();
			foreach ($result as $key =>$val){
				$category[$val['id']] = $val['name'];
			}
			S('vocabulary_list', $category);
		}
		return $category;
  }

	/**
	 * 获取全部分类
	 * @param unknown_type $vid
	 * @param int $vid 类型ID号
	 */
	public static function get_category_list( $vid = self::TYPE_CATEGORY)
	{
		global $language_id;
		$categoryList = array();
		$cache_id = 'category_list_'.$vid.'_'.$language_id;

		/*if(S($cache_id)){
			$categoryList = S($cache_id);
		}else{*/
			$category_db = D('category');
			$where = array(
				'display' => 1,
				'vid' => $vid,
				'language_id' => C('language_id'),
				//'language_id' => $language_id ? intval($language_id) : C('language_id'),
			);
			$category_db->field('id,parentid,img,adv_img,ci.name');
			$category_db->join('category_items AS ci ON ci.category_id = category.id');
			$category_db->where($where);
			$result = $category_db->select();

            if($result){
				$j = 0;
				foreach ($result as $row){
					$category_items_db02 = D('category_items');
					$category_items_db02->field('name,meta_title,meta_keywords,meta_description,items_img,items_adv_img');
					$categoryInfo02 = $category_items_db02->where(array('category_id' => $row['id'], 'language_id' => $language_id))->find();
					if(!$categoryInfo02){
						$categoryInfo02 = $category_items_db02->where(array('category_id' => $row['id'], 'language_id' => C('language_id')))->find();
					}
                    if($row['parentid'] != 0){
                        $parent_name = M('category_items')->field('name')->where('language_id='.$language_id.' and category_id = '.$row['parentid'])->find();
                        $category_list[$j]['parent_name'] = $parent_name['name'];
                    }
					$category_list[$j]['id'] 		= $row['id'];
					$category_list[$j]['parentid'] 	= $row['parentid'];
					$category_list[$j]['img'] 		= $categoryInfo02['items_img']?$categoryInfo02['items_img']:$row['img'];
					$category_list[$j]['adv_img'] 		= $categoryInfo02['items_adv_img']?$categoryInfo02['items_adv_img']:$row['adv_img'];//分类banner图片
					$category_list[$j]['name'] 		= $categoryInfo02['name'];
					$category_list[$j]['meta_title'] 		= $categoryInfo02['meta_title'];
					$category_list[$j]['meta_keywords'] 		= $categoryInfo02['meta_keywords'];
					$category_list[$j]['meta_description'] 		= $categoryInfo02['meta_description'];
					$j++;
				}
			}
 
//			echo $category_db->getLastSql();exit;
			foreach ($category_list as $key =>$val){
				switch ($vid)
				{
					case self::TYPE_ARTICLE : {
						$val['url'] = U('article/articlelist', 'catid='. $val['id']);
						break;
					}
					case self::TYPE_ARTICLE_RECOMMEND : {
						$val['url'] = url('article_type', 'rid='. $val['id']);
						break;
					}
					case self::TYPE_CATEGORY : {
						$val['url'] = url('category', 'cid='. $val['id']);
						break;
					}
					case self::TYPE_BRAND : {
						$val['url'] = url('category', 'bid='. $val['id']);
						break;
					}
					case self::TYPE_RECOMMEND : {
						$val['url'] = url('category', 'rid='. $val['id']);
						break;
					}
				}

				$categoryList[$val['id']] = $category_list[$key];
			}
			/*S($cache_id, $categoryList);
		}*/
		return $categoryList;
	}

	/**
	 * 获取分类信息
	 * @param int $catid 分类ID号
	 * @param int $vid 类型ID号
	 */
	public static function get_category_info($catid, $vid = self::TYPE_CATEGORY)
	{
		if(!$vid){
			$catdb = D('category');
			$vid = $catdb->where('id='.$catid)->getField('vid');
			if(!$vid){
				return false;
			}
		}
		$category_list = self::get_category_list($vid);
		return isset($category_list[$catid]) ? $category_list[$catid] : false;
	}



	public static function get_category_info2233($catid, $vid = self::TYPE_CATEGORY)
	{
		$where = array(
			'vid'=>$vid,
			'language_id' => C('language_id'),
		);
			$catdb = D('category');
			$catdb->field('category.id,category.parentid,category.display,category.listorder,category.model_id,ci.name');
			$catdb->join('category_items AS ci ON ci.category_id = category.id');
			if($vid == self::TYPE_BRAND){
				$catdb->order('ci.name ASC');
			}else{
				$catdb->order('category.listorder DESC, category.id DESC');
			}
			$category = $catdb->where($where)->select();
			//dump($category);exit;
		return $category;
	}

	/**
	 * 逐级向上查找分类图片
	 * @param array $category 分类图片
	 */
	public static function get_parent_category_advImg($category)
	{
		$adv_img = '';
			if(empty($category['adv_img']) && $category['parentid']){
				$parentInfo = self::get_category_info($category['parentid'], $category['vid']);
				if($parentInfo){
					if(empty($parentInfo['adv_img']) && $parentInfo['parentid']){
						$parentInfo2 = self::get_category_info($parentInfo['parentid'], $parentInfo['vid']);
						if($parentInfo2){
							if(empty($parentInfo2['adv_img']) && $parentInfo2['parentid']){
								$parentInfo3 = self::get_category_info($parentInfo2['parentid'], $parentInfo2['vid']);
								if($parentInfo3 && $parentInfo3['adv_img']){
									$adv_img = $parentInfo3['adv_img'];
								}
							}elseif ($parentInfo2['adv_img']){
								$adv_img = $parentInfo['adv_img'];
							}
						}
					}elseif ($parentInfo['adv_img']){
						$adv_img = $parentInfo['adv_img'];
					}
				}
			}
		return $adv_img;
	}

	/**
	 * 获取简单分类列表
	 * @param int $vid 分类类型ID
	 */
	public static function get_category_list_base($vid = self::TYPE_CATEGORY, $parentid = NULL)
	{
		global $language_id;
		//$url = A('web/common');
		
		//$ss = $url->generateUrl_un($str);
		//dump($ss);
		$categoryList = array();
		/*$cache_id = 'category_list_base_'.$vid.'_'.$language_id;
		if(S($cache_id)){
			$categoryList = S($cache_id);
		}else{*/
			$category_db = D('category');
			$where = array(
				'display' => 1,
				'vid' => $vid,
				'language_id' => C('language_id'),
				//'language_id' => $language_id ? intval($language_id) : C('language_id'),
			);
			if($parentid !== NULL) $where['parentid'] = $parentid;

			$category_db->field('id,parentid,img,ci.name,is_3d');
			$category_db->join('category_items AS ci ON ci.category_id = category.id');
			$category_db->where($where);
			if($vid == self::TYPE_BRAND){
				$category_db->order('ci.name ASC');
			}else{
				$category_db->order('listorder DESC, id DESC');
			}
			$categoryList = $category_db->select();

			if($categoryList){
				$j = 0;
				foreach ($categoryList as $row){
					$category_items_db02 = D('category_items');
					$category_items_db02->field('name');
					$categoryInfo02 = $category_items_db02->where(array('category_id' => $row['id'],'language_id' => $language_id))->find();
					if(!$categoryInfo02){
						$categoryInfo02 = $category_items_db02->where(array('category_id' => $row['id'], 'language_id' => C('language_id')))->find();
					}
					$category_list[$j]['id'] 		= $row['id'];
					$category_list[$j]['parentid'] 	= $row['parentid'];
					$category_list[$j]['img'] 		= $row['img'];
                    $category_list[$j]['is_3d'] 		= $row['is_3d'];
					$category_list[$j]['name'] 		= $categoryInfo02['name'];
					$j++;
				}
			}

			/*if(empty($categoryList)){
				$where = array(
					'display' => 1,
					'vid' => $vid,
					'language_id' => C('language_id'),
				);
				$category_db->field('id,parentid,img,ci.name');
				$category_db->join('category_items AS ci ON ci.category_id = category.id');
				$categoryList = $category_db->where($where)->order('listorder DESC, id DESC')->select();
			}*/

			if($category_list){
				foreach ($category_list as &$cat){
				/*if(empty($cat['name'])){
					$cat['name'] = D('category_items')->where(array('category_id' => $cat['id'], 'language_id' => C('language_id')))->getField('name');
				}*/
					switch ($vid)
					{
						case self::TYPE_ARTICLE : {
							$cat['url'] = url('/article_type/'. $cat["id"].'-'.generateUrl_un($cat["name"]));
							//$cat['url'] = url('article_type', 'id='. $cat['id']);
							break;
						}
						case self::TYPE_ARTICLE_RECOMMEND : {
							$cat['url'] = url('article_type', 'rid='. $cat['id']);
							break;
						}
						case self::TYPE_CATEGORY : {
							//$cat['url'] = url('category', 'cid='. $cat['id']);
							$catgory = D('category_items')->where(array('category_id' => $cat['id'], 'language_id' =>1))->find();
							$cat['url'] = url('/category/'.$cat["id"].'-'.generateUrl_un($catgory["name"]));
							$cat['URL_PATH_INFO'] = '/category/'.$cat["id"].'-'.generateUrl_un($catgory["name"]);
							break;
						}
						case self::TYPE_BRAND : {
							$cat['url'] = url('category', 'bid='. $cat['id']);
							break;
						}
						case self::TYPE_RECOMMEND : {
							$cat['url'] = url('category', 'rid='. $cat['id']);
							break;
						}
					}
				}
			}
			/*S($cache_id, $categoryList);
		}*/
		return $category_list;
	}

	/**
	 * 获取简单分类列表
	 * @param int $vid 分类类型ID
	 */
	public static function get_category_list_base02($vid = self::TYPE_CATEGORY)
	{
		global $language_id;
		$categoryList = array();
		/*$cache_id = 'category_list_base_'.$vid.'_'.$language_id;
		if(S($cache_id)){
			$categoryList = S($cache_id);
		}else{*/
			$category_db = D('category');
			$where = array(
				'display' => 1,
				'vid' => $vid,
				'language_id' => C('language_id'),
			);
			$category_db->field('id,parentid,img,ci.name');
			$category_db->join('category_items AS ci ON ci.category_id = category.id');
			$category_db->where($where);
			if($vid == self::TYPE_BRAND){
				$category_db->order('ci.name ASC');
			}else{
				$category_db->order('listorder DESC, id DESC');
			}
			$categoryList = $category_db->select();

			if($categoryList){
				foreach ($categoryList as $row){
					$category_items_db = D('category_items');
					$category_items_db->field('name');
					$categoryInfo = $category_items_db->where(array('category_id' => $row['id'], 'language_id' => $language_id))->find();
					if(!$categoryInfo){
						$categoryInfo = $category_items_db->where(array('category_id' => $row['id'], 'language_id' => C('language_id')))->find();
					}
					$categoryList['id'] 		= $row['id'];
					$categoryList['parentid'] 	= $row['parentid'];
					$categoryList['img'] 		= $row['img'];
					$categoryList['id'] 		= $categoryInfo['name'];

				}
			}


			/*S($cache_id, $categoryList);
		}*/
		return $categoryList;
	}

	/**
	 * 获取分类的子类列表
	 * @param int $parent_id 上级分类ID
	 * @param int $vid 分类类型ID
	 */
	public static function get_category_sub_list($parent_id, $vid = self::TYPE_CATEGORY)
	{
		$subCategoryList = array();
		$categoryList = self::get_category_list_base($vid,$parent_id);
		// if($categoryList){
		// 	foreach ($categoryList as $cat){
		// 		if($cat['parentid'] == $parent_id)
		// 			$subCategoryList[] = $cat;
		// 	}
		// }
		// return $subCategoryList;
		return $categoryList;
	}

	/**
	 * 树型下拉选择分类
	 * @param int $selectid 选中ID号
	 * @param int $vid 分类类型ID
	 * @param string $str 下拉样式
	 */
	public static function select_list($selectid = 0, $vid = self::TYPE_CATEGORY, $str  = "<option value='\$id' \$selected>\$spacer \$name</option>")
	{
		$category = self::get_category_list_base($vid);
		import('COM.Tree');
		$tree = new Tree();
		$array = array();
		foreach($category as $r) {
			$r['selected'] = $r['id'] == $selectid ? 'selected' : '';
			$array[] = $r;
		}
	//	$str  = "<option value='\$id' \$selected>\$spacer \$name</option>";

		$tree->init($array);
		$select_categorys = $tree->get_tree(0, $str);
		return $select_categorys;
	}

	/**
	 * 获取分类的所有子类多维数组
	 * @param unknown_type $cid 当前分类ID
	 * @param unknown_type $vid 类型ID
	 * @return string
	 */
	public static function get_category_child_list($cid=0, $vid=self::TYPE_CATEGORY)
	{
		$categorys = array();
		$categoryList = self::get_category_list_base($vid);
		if(is_array($categoryList)){
			require_cache(EXTEND_PATH.'Function/extend.php');
			$categorys = list_to_tree($categoryList, 'id', 'parentid', 'children', $cid);
		}
		return $categorys ? $categorys : false;
	}

	/**
	 * 获取分类的所有子类ID
	 * @param int $catid 分类ID
	 * @param int $vid 类型ID
	 * @return string
	 */
	public static function get_category_child_ids($cid=0, $vid=self::TYPE_CATEGORY)
	{
		$cacheId = 'category_child_ids_'.$cid;
		$catIds = '';
		if(S($cacheId)){
			$catIds = S($cacheId);
		}else{
			$ids = '';
			$categorys = self::get_category_child_list($cid, $vid);
			if($categorys){
				foreach ($categorys as $cat){
					$ids[] = $cat['id'];
				}
			}
			$ids[] = $cid;
			$catIds = join(',', $ids);
			S($cacheId, $catIds);
		}
		return $catIds;
	}

	/**
	 * 返回分类的路径
	 * @param int $catid 分类ID
	 * @param int $vid 类型ID
	 * return array
	 */
	public static function get_category_pos($cid, $vid = self::TYPE_CATEGORY)
	{
		$pathArray = array();
		$categoryArray = array();
    	$categoryList = CategoryModel::get_category_list_base($vid);
    	foreach ($categoryList as $cate){
    		$categoryArray[$cate['id']] = $cate;
    	}
    import('COM.Tree');
    $tree = new Tree();
    $tree->init($categoryArray);
    $tree->get_pos($cid, $pathArray);
    return $pathArray;
	}

	/**
	 * 获取分类下的品牌
	 * @param int $cid 分类ID
	 */
	public static function get_brand_list_by_cat_id($cid)
	{
		if(intval($cid)==0) return array();
		$cids = self::get_category_child_ids($cid);
		$map['catid'] = array('IN', $cids);
		$map['brand_id'] = array(array('gt', 0), array('exp', 'IS NOT NULL'));

		$product_db = D('product');

		$brind_ids = $product_db->field('brand_id')->where($map)->group('brand_id')->cache(true, C('DB_CACHE_TIME'))->select();
//		echo $product_db->getLastSql();
		$brandList = array();
		if($brind_ids){
			foreach ($brind_ids as $brand){
				$info = self::get_category_info($brand['brand_id'], self::TYPE_BRAND);
				if($info)
					$brandList[] = $info;
			}
		}
		return $brandList;
	}
/**
	 * 获取全部分类
	 * @param int $vid 类型ID号
	 */
	public static function getCategoryList( $vid = self::TYPE_CATEGORY)
	{
		global $language_id;
		$where = array(
			'vid'=>$vid,
			'language_id' => $language_id,
		);
			$catdb = D('category');
			$catdb->field('category.id,category.parentid,category.display,category.listorder,category.model_id,ci.name,category.img,category.adv_img');
			$catdb->join('category_items AS ci ON ci.category_id = category.id');
			if($vid == self::TYPE_BRAND){
				$catdb->order('ci.name ASC');
			}else{
				$catdb->order('category.listorder DESC, category.id DESC');
			}
			$category = $catdb->where($where)->select();
			//dump($category);exit;
		return $category;
	}

	/**
	 * 返回分类的父ID
	 * @param int $catid 分类ID
	 * return int $parentid
	 */
	public static function get_category_parentid($cid)
	{
        $catdb = D('category');
		$catdb->where(array('id' => $cid)); 
		$parentid = $catdb->getField('parentid');      
        return $parentid;
	}

	/**
	 * 返回分类的URL
	 * @param int $catid 分类ID
	 * return string $url
	 */
	public static function get_category_one_url($cid)
	{
	    $category_itemsdb = D('category_items');
		$catgory = $category_itemsdb->where(array('category_id' => $cid, 'language_id' =>1))->find();
		if(!$catgory){
			return '';
		}
		$url = '/category/'.$cid.'-'.generateUrl_un($catgory["name"]);  
        return $url;
	}

	/**
	 * 返回全部分类id
	 * @param unknown_type $vid
	 * @param int $vid 类型ID号
	 */
	public static function get_category_id_array( $vid = self::TYPE_CATEGORY)
	{
		global $language_id;
        
        if(S('category_id_array_'.$vid)){
        	return S('category_id_array_'.$vid);
        }

		$category_db = D('category');
		$where = array(
			'display' => 1,
			'vid' => $vid,
		);
		$category_db->field('id');
		$category_db->where($where);
		$result = $category_db->select();
        
        $ID = array();
        foreach ($result as $val) {
        	$ID[] = $val['id'];
        }

        S('category_id_array_'.$vid, $ID);
	    return $ID;
	}

}